package com.qf.listener;

import com.netflix.discovery.converters.Auto;
import com.qf.consants.RabbitMQConstants;
import com.qf.entity.Email;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;

@Component
public class EmailQueueListener {

    @Value("${spring.mail.username}")
    private String fromUser; // xxx@3

    @Autowired
    private JavaMailSender javaMailSender;


    @RabbitListener(queues = RabbitMQConstants.EMAIL_QUEUE)
    public void sendEmail(Email email, Channel channel, Message message) throws MessagingException {
        System.out.println(email);
        try {

            // 1.创建一个MimeMessage
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();

            // 2.使用MimeMessageHelper来封装邮件信息
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

            helper.setSubject(email.getTitle());
            helper.setText(email.getContent());
            helper.setTo(email.getToUser());
            if (!StringUtils.isEmpty(email.getCcUser())) {
                helper.setCc(email.getCcUser());
            }
            helper.setFrom(fromUser); // 发件人

            // 3.发送邮件
//            javaMailSender.send(mimeMessage);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
